package com.xdap.keymen.service.punch;

import com.definesys.mpaas.query.MpaasQuery;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.xdap.keymen.entity.*;
import com.xdap.motor.entity.SnowflakeIdWorker;
import com.xdap.motor.vo.ResponseVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@RequiredArgsConstructor
@Slf4j
public class PunchContactPersonService  extends PunchBaseService{
    private final SnowflakeIdWorker snowflakeIdWorker;

    public ResponseVo getContactPersonList(String rv) {
        //为空则到表中取
        if (StringUtils.isEmpty(rv)) {
            rv=getMaxRvid("punch_sales_contact").toString();
        }
        Gson gson = new GsonBuilder().create();
        Map<String, String> params=new HashMap<>();
        Map<String, String> headers=new HashMap<>();
        //每页条数
        int sz=8;
        //页面
        int pg=1;
        //记录总数
        //int maxCount=this.countEmployees(rv);
        int maxCount=2;
        log.info("最大记录数maxCount:{}",maxCount);
        // 计算总页数 (向上取整)
        int totalPages = (int) Math.ceil((double) maxCount / sz);
        for (int currentPage = pg; currentPage <= totalPages; currentPage++) {
            headers=new HashMap<>();
            headers.put("Authorization", "Bearer "+getPunchToken());
            String response = okHttpUtils.doGet(getPunchUrl().concat("/CRM/api/custshiptoinvaddr/"+rv+"/"+sz+"/"+currentPage), params,headers);
            PunchResponse punchResponse = gson.fromJson(response, new TypeToken<PunchResponse>(){}.getType());
            List<PunchShippingToResponseEntity> list = gson.fromJson(punchResponse.getResult(), new TypeToken<List<PunchShippingToResponseEntity>>(){}.getType());
            for(PunchShippingToResponseEntity punchShippingToResponseEntity:list){
                //saveOrUpdateContactPerson(punchShippingToResponseEntity);
            }

            // 如果已经是最后一页，退出循环
            if (currentPage == totalPages) {
                break;
            }
        }

        return ResponseVo.ok().setData(maxCount);
    }

    public ResponseVo getCustshiptoinvaddrPerson(String custnum,String tabId) {

        Gson gson = new GsonBuilder().create();
        Map<String, String> params=new HashMap<>();
        Map<String, String> headers=new HashMap<>();
        headers.put("Authorization", "Bearer "+getPunchToken());
        String response = okHttpUtils.doGet(getPunchUrl().concat("/CRM/api/custshiptoinvaddr/"+custnum), params,headers);
        PunchResponse punchResponse = gson.fromJson(response, new TypeToken<PunchResponse>(){}.getType());
        List<PunchShippingToResponseEntity> list = gson.fromJson(punchResponse.getResult(), new TypeToken<List<PunchShippingToResponseEntity>>(){}.getType());
        for(PunchShippingToResponseEntity punchShippingToResponseEntity:list){
            saveOrUpdateContactPerson(punchShippingToResponseEntity,tabId);
        }

        return ResponseVo.ok();
    }

    private void saveOrUpdateContactPerson(PunchShippingToResponseEntity entity,String tabId) {
       String contactType="";
       if(removeSpaces(entity.getCategory()).equals("S")){
           contactType="3";
       }else if(removeSpaces(entity.getCategory()).equals("B")){
           contactType="2";
       }
        String currentTenantId = runtimeAppContextService.getCurrentTenantId();
        MpaasQuery query = runtimeDatasourceService.buildTenantMpaasQuery("xdap_app_" + currentTenantId);
        query.sql("select id from punch_sales_contact where client_number='"+removeSpaces(entity.getCust_num())+"' and contact_name='"+removeSpaces(entity.getContact_ship())+"'");
        String id= query.doQueryFirst(String.class);
        if (id!=null) {
            //更新
            query = runtimeDatasourceService.buildTenantMpaasQuery("xdap_app_" + currentTenantId);

            query.update("client_number",removeSpaces(entity.getCust_num()));
            query.update("contact_name",removeSpaces(entity.getContact_ship()));
            query.update("mobile_number",removeSpaces(entity.getPhone_ship()));
            query.update("email",removeSpaces(entity.getShip_mail()));
            query.update("contact_type",contactType);
            query.update("client_name",removeSpaces(entity.getName()));
            query.update("cust_seq",removeSpaces(entity.getCust_seq()));
            query.update("phone_number",removeSpaces(entity.getFax_ship()));
            query.update("city",removeSpaces(entity.getCity()));
            query.update("county",removeSpaces(entity.getCounty()));
            query.update("state",removeSpaces(entity.getState()));
            query.update("country",removeSpaces(entity.getCountry()));
            query.update("address",removeSpaces(entity.getAddr_1()));
            query.update("rvid",entity.getRvid());
            query.eq("id", id);
            query.doUpdate(PunchSalesContactEntity.class);
        }else{
            //新增
            PunchSalesContactEntity punchSalesContactEntity = new PunchSalesContactEntity();
            punchSalesContactEntity.setId(snowflakeIdWorker.nextId());
            punchSalesContactEntity.setDocumentId(snowflakeIdWorker.nextId());
            punchSalesContactEntity.setClientNumber(removeSpaces(entity.getCust_num()));
            punchSalesContactEntity.setContactName(removeSpaces(entity.getContact_ship()));
            punchSalesContactEntity.setMobileNumber(removeSpaces(entity.getPhone_ship()));
            punchSalesContactEntity.setEmail(removeSpaces(entity.getShip_mail()));
            punchSalesContactEntity.setContactType(contactType);
            punchSalesContactEntity.setClientName(removeSpaces(entity.getName()));
            punchSalesContactEntity.setCustSeq(removeSpaces(entity.getCust_seq()));
            punchSalesContactEntity.setPhoneNumber(removeSpaces(entity.getFax_ship()));
            punchSalesContactEntity.setTabDocId(tabId);
            punchSalesContactEntity.setCity(removeSpaces(entity.getCity()));
            punchSalesContactEntity.setCounty(removeSpaces(entity.getCounty()));
            punchSalesContactEntity.setState(removeSpaces(entity.getState()));
            punchSalesContactEntity.setCountry(removeSpaces(entity.getCountry()));
            punchSalesContactEntity.setAddress(removeSpaces(entity.getAddr_1()));
            punchSalesContactEntity.setRvid(entity.getRvid());
            query = runtimeDatasourceService.buildTenantMpaasQuery("xdap_app_" + currentTenantId);
            query.doInsert(punchSalesContactEntity);

        }

    }
    public ResponseVo getCustShiptoPerson(String custnum,String tabId) {

        Gson gson = new GsonBuilder().create();
        Map<String, String> params=new HashMap<>();
        Map<String, String> headers=new HashMap<>();
        headers.put("Authorization", "Bearer "+getPunchToken());
        String response = okHttpUtils.doGet(getPunchUrl().concat("/CRM/api/custshipto/"+custnum), params,headers);
        PunchResponse punchResponse = gson.fromJson(response, new TypeToken<PunchResponse>(){}.getType());
        List<PunchShippingToResponseEntity> list = gson.fromJson(punchResponse.getResult().replace("\"name\":","\"Name\":"), new TypeToken<List<PunchShippingToResponseEntity>>(){}.getType());
        for(PunchShippingToResponseEntity punchShippingToResponseEntity:list){
            saveOrUpdateContactPerson(punchShippingToResponseEntity,tabId);
        }

        return ResponseVo.ok();
    }
}
